﻿//-----------------------------------------------------------------------
// <copyright file="BidderRepository.cs" company="Transilvania University of Brasov">
//     Copyright (c) Nagy Robert. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

namespace DataAccessLayer.Auctioneer
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Common;

    using DomainModel;
    using Microsoft.Practices.EnterpriseLibrary.Data;
    using Microsoft.Practices.EnterpriseLibrary.Validation;

    /// <summary>
    /// Implements database operations for the Bidder
    /// </summary>
    /// <seealso cref="IBidderRepository" />
    public class BidderRepository : IBidderRepository
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="AuctioneerRepository"/> class.
        /// </summary>
        public BidderRepository()
        {
            DatabaseFactory.ClearDatabaseProviderFactory();
            DatabaseFactory.SetDatabaseProviderFactory(new DatabaseProviderFactory());
        }

        /// <summary>
        /// Adds the specified data transfer object.
        /// </summary>
        /// <param name="dto">The data transfer object.</param>
        /// <exception cref="ArgumentException">Invalid data transfer object</exception>
        public void Add(DTOBidder dto)
        {
            ValidationResults validationResults = Validation.Validate(dto);
            if (!validationResults.IsValid)
            {
                string errorMessage = string.Empty;
                foreach (var current in validationResults)
                {
                    errorMessage += current.Message + "\n";
                }

                throw new ArgumentException(errorMessage);
            }

            Database database = DatabaseFactory.CreateDatabase("MyConStr");
            using (DbCommand command = database.GetStoredProcCommand("AddBidder"))
            {
                database.AddInParameter(command, "@username", DbType.String, dto.Username);
                database.AddInParameter(command, "@firstname", DbType.String, dto.FirstName);
                database.AddInParameter(command, "@lastname", DbType.String, dto.LastName);
                database.AddInParameter(command, "@password", DbType.String, dto.Password);
                database.AddOutParameter(command, "@id", DbType.Int32, 255);

                database.ExecuteNonQuery(command);
                dto.Id = (int)database.GetParameterValue(command, "@id");
            }
        }

        /// <summary>
        /// Deletes the specified identifier.
        /// </summary>
        /// <param name="id">The identifier.</param>
        /// <exception cref="ArgumentException">Id should be greater than 0.</exception>
        public void Delete(int id)
        {
            if (id < 1)
            {
                throw new ArgumentException("Id should be greater than 0.");
            }

            Database database = DatabaseFactory.CreateDatabase("MyConStr");
            using (DbCommand command = database.GetStoredProcCommand("DeleteBidder"))
            {
                database.AddInParameter(command, "@id", DbType.Int32, id);
                database.ExecuteNonQuery(command);
            }
        }

        /// <summary>
        /// Edits the specified data transfer object.
        /// </summary>
        /// <param name="dto">The data transfer object.</param>
        /// <exception cref="ArgumentException">Invalid data transfer object</exception>
        public void Edit(DTOBidder dto)
        {
            ValidationResults validationResults = Validation.Validate(dto);
            if (!validationResults.IsValid)
            {
                string errorMessage = string.Empty;
                foreach (var current in validationResults)
                {
                    errorMessage += current.Message + "\n";
                }

                throw new ArgumentException(errorMessage);
            }

            Database database = DatabaseFactory.CreateDatabase("MyConStr");
            using (DbCommand command = database.GetStoredProcCommand("EditBidder"))
            {
                database.AddInParameter(command, "@id", DbType.Int32, dto.Id);
                database.AddInParameter(command, "@username", DbType.String, dto.Username);
                database.AddInParameter(command, "@firstname", DbType.String, dto.FirstName);
                database.AddInParameter(command, "@lastname", DbType.String, dto.LastName);
                database.AddInParameter(command, "@password", DbType.String, dto.Password);

                database.ExecuteNonQuery(command);
            }
        }

        /// <summary>
        /// Finds the specified identifier.
        /// </summary>
        /// <param name="id">The identifier.</param>
        /// <returns>Data transfer object</returns>
        /// <exception cref="ArgumentException">Id should be greater than 0.</exception>
        public DTOBidder Find(int id)
        {
            if (id < 1)
            {
                throw new ArgumentException("Id should be greater than 0.");
            }

            Database database = DatabaseFactory.CreateDatabase("MyConStr");
            using (DbCommand command = database.GetStoredProcCommand("FindBidder"))
            {
                database.AddInParameter(command, "@id", DbType.Int32, id);
                using (IDataReader reader = database.ExecuteReader(command))
                {
                    if (reader.Read())
                    {
                        DTOBidder result = new DTOBidder();
                        result.FirstName = reader["FirstName"]?.ToString();
                        result.Id = (int)reader["id"];
                        result.LastName = reader["LastName"]?.ToString();
                        result.Password = reader["Password"]?.ToString();
                        result.Username = reader["Username"]?.ToString();
                        return result;
                    }
                }
            }

            return null;
        }

        /// <summary>
        /// Gets all.
        /// </summary>
        /// <returns>List of data transfer objects</returns>
        public List<DTOBidder> GetAll()
        {
            List<DTOBidder> resultList = new List<DTOBidder>();
            Database database = DatabaseFactory.CreateDatabase("MyConStr");
            using (IDataReader reader = database.ExecuteReader(CommandType.StoredProcedure, "GetAllBidders"))
            {
                while (reader.Read())
                {
                    DTOBidder dto = new DTOBidder();
                    dto.FirstName = reader["FirstName"]?.ToString();
                    dto.Id = (int)reader["Id"];
                    dto.LastName = reader["LastName"]?.ToString();
                    dto.Password = reader["Password"]?.ToString();
                    dto.Username = reader["Username"]?.ToString();
                    resultList.Add(dto);
                }
            }

            return resultList;
        }
    }
}
